var util = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // hasCarNum: 0,
    lists: [],
    Allselected: false,
    totalPrice: true,
    selectAllStatus: false,
    totalNum: 0,
    disabled: true,
    startX: 0,
    startY: 0,
    hasCarNum: false,

    ordlists: {
      lists: [],
      totalPrice: '',
      totalNum: '',
    },

    noordlists: {
      lists: [],
      totalPrice: '',
      totalNum: '',
    },

    checklogin: true,

    shopsGood: [{
      goodlist: []
    }],

    ordcheck: true,

    shoplist: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // 存储数组函数
  upLists(e) {
    var that = this
    var lis = []
    let shopsGood = that.data.shopsGood;
    for (let i = 0; i < shopsGood.length; i++) {
      for (let j = 0; j < shopsGood[i].goodlist.length; j++) {
        for (let k = 0; k < that.data.lists.length; k++) {
          if (that.data.lists[k].id == shopsGood[i].goodlist[j].id) {
            lis = lis.concat(that.data.shopsGood[i].goodlist[j])
          }
        }
      }

    }

    wx.setStorage({
      key: 'lists',
      data: lis
    })
  },

  // 计算手滑动角度函数
  angle: function(start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  // 存储购物车数量数据函数
  getCarNum(e) {
    let num = 0;
    var that = this
    let shopsGood = that.data.shopsGood;
    for (let i = 0; i < shopsGood.length; i++) {
      for (let j = 0; j < shopsGood[i].goodlist.length; j++) {
        num++
      }
    }
    wx.setStorage({
      key: 'carNum',
      data: num
    })

    util.buycarBar()
  },

  // 取得购物车数量数据函数
  PutCarNum(e) {
    wx.getStorage({
      key: 'carNum',
      success: (res) => {
        this.setData({
          hasCarNum: res.data
        })
      },

    })
  },

  //  总价计算函数封装
  getTotalPrice(e) {
    var that = this
    let shopsGood = that.data.shopsGood;
    let total = 0;
    for (let i = 0; i < shopsGood.length; i++) {
      for (let j = 0; j < shopsGood[i].goodlist.length; j++) {
        if (shopsGood[i].goodlist[j].selected) {
          total += shopsGood[i].goodlist[j].num * shopsGood[i].goodlist[j].retailPrice;
        }
      }
    }
    that.setData({
      totalPrice: total.toFixed(2)
    })
  },

  // 总和计算函数封装
  getTotalNum(e) {
    var that = this
    let shopsGood = that.data.shopsGood;
    let total = 0;
    for (let i = 0; i < shopsGood.length; i++) {
      for (let j = 0; j < shopsGood[i].goodlist.length; j++) {
        if (shopsGood[i].goodlist[j].selected) {
          total += JSON.parse(shopsGood[i].goodlist[j].num);
        }
      }
    }
    that.setData({
      totalNum: total,
    })
    console.log('totalNum' + that.data.totalNum)
  },

  touchstart(e) {
    var that = this
    let shopsGood = that.data.shopsGood;
    //开始触摸时 重置所有删除
    for (let i = 0; i < shopsGood.length; i++) {
      that.data.shopsGood[i].goodlist.forEach(function(v, i) {
        if (v.isTouchMove) //只操作为true的
          v.isTouchMove = false;
      })
      // console.log(e.changedTouches[0].clientX)
      // console.log(e.changedTouches[0].clientY)
      // console.log(e)
      this.setData({
        startX: e.touches[0].clientX,
        startY: e.touches[0].clientY,
        shopsGood: that.data.shopsGood
      })
    }

  },



  //滑动事件处理
  touchmove(e) {
    let id = e.currentTarget.dataset.id; //当前索引
    let startX = this.data.startX; //开始X坐标
    let startY = this.data.startY; //开始Y坐标
    let touchMoveX = e.touches[0].clientX; //滑动变化坐标
    let touchMoveY = e.touches[0].clientY; //滑动变化坐标
    //获取滑动角度
    let angle = this.angle({
      X: startX,
      Y: startY
    }, {
      X: touchMoveX,
      Y: touchMoveY
    });
    for (let j = 0; j < this.data.shopsGood.length; j++) {
      this.data.shopsGood[j].goodlist.forEach((v, i) => {
        v.isTouchMove = false
        //滑动超过30度角 return
        if (Math.abs(angle) > 30) return;
        if (this.data.shopsGood[j].goodlist[i].goodsId == id) {
          if (touchMoveX > startX) //右滑
            v.isTouchMove = false
          else //左滑
            v.isTouchMove = true
        }
      })
    }

    //更新数据
    this.setData({
      shopsGood: this.data.shopsGood
    })
  },


  del(e) {
    let Allselected = this.data.Allselected;
    let selectAllStatus = this.data.selectAllStatus;
    const id = e.currentTarget.dataset.id;

    let shopsGood = this.data.shopsGood;
    for (var x = 0; x < shopsGood.length; x++) {
      for (var y = 0; y < shopsGood[x].goodlist.length; y++) {
        if (shopsGood[x].goodlist[y].goodsId == id) {
          shopsGood[x].goodlist.splice(y, 1)

          if (shopsGood[x].goodlist.length == 0) {
            shopsGood.splice(x, 1)
            this.setData({
              shopsGood: shopsGood,
            })
            break;
          }

          this.setData({
            shopsGood: shopsGood,
          })

        }
      }
    }

    if (!this.data.shopsGood.length) {
      this.setData({
        hasCarNum: false,
      })
    }

    this.upLists();
    this.getTotalNum();
    this.getCarNum();
    this.getTotalPrice();
    this.onShow();
  },

  //店铺选择shoplist
  shopicon(e) {
    var that = this
    let shopsGood = that.data.shopsGood;
    const index = JSON.parse(e.currentTarget.dataset.index);
    var shoplist = that.data.shoplist

    if (shoplist[index]) {
      for (var y = 0; y < shopsGood[index].goodlist.length; y++) {
        shopsGood[index].goodlist[y].selected = false
      }
      shoplist[index] = false
      that.setData({
        shoplist: shoplist,
        shopsGood: shopsGood,
      })
    } else {
      for (var y = 0; y < shopsGood[index].goodlist.length; y++) {
        shopsGood[index].goodlist[y].selected = true
      }
      shoplist[index] = true
      that.setData({
        shoplist: shoplist,
        shopsGood: shopsGood,
      })
    }

    var disnum = 0;
    var allsel = 0
    for (var x = 0; x < shopsGood.length; x++) {
      for (var y = 0; y < shopsGood[x].goodlist.length; y++) {
        if (shopsGood[x].goodlist[y].selected) {
          disnum++
        }
        if (!shopsGood[x].goodlist[y].selected) {
          allsel++
        }
      }
    }
    if (disnum == 0) {
      this.setData({
        disabled: true
      })
    } else {
      this.setData({
        disabled: false
      })
    }

    if (allsel !== 0) {
      this.setData({
        Allselected: false,
        selectAllStatus: false
      })
    } else {
      this.setData({
        Allselected: true,
        selectAllStatus: true
      })
    }

    this.getTotalPrice();
    this.getTotalNum();
    this.getCarNum();
    this.upLists();

  },

  //商品的选择
  iconSelect(e) {
    console.log(e)
    let shopsGood = this.data.shopsGood;
    let disabled = this.data.disabled;
    let selectAllStatus = this.data.selectAllStatus;
    let Allselected = this.data.Allselected;
    const id = e.currentTarget.dataset.id;
    var k = 0
    var shoplist = this.data.shoplist

    for (var x = 0; x < shopsGood.length; x++) {
      for (var y = 0; y < shopsGood[x].goodlist.length; y++) {
        if (shopsGood[x].goodlist[y].goodsId == id) {

          const select = shopsGood[x].goodlist[y].selected;
          shopsGood[x].goodlist[y].selected = !select;

          this.setData({
            shopsGood: shopsGood,
            Allselected: !Allselected,
            selectAllStatus: !selectAllStatus
          })

          for (var i = 0; i < shopsGood.length; i++) {
            for (var j = 0; j < shopsGood[i].goodlist.length; j++) {
              if (!shopsGood[i].goodlist[j].selected) {
                this.setData({
                  selectAllStatus: false,
                  Allselected: false,
                })
              }
            }
          }

          for (var j = 0; j < shopsGood[x].goodlist.length; j++) {
            if (shopsGood[x].goodlist[j].selected) {
              k++
            }
          }
          if (k == 0) {
            shoplist[x] = false
            this.setData({
              shoplist: shoplist
            })
          } else {
            shoplist[x] = true
            this.setData({
              shoplist: shoplist
            })
          }



          this.getTotalNum();
          this.getTotalPrice();
          if (this.data.totalPrice == false) {
            this.setData({
              disabled: true
            })
          } else {
            this.setData({
              disabled: false
            })
          }


        }
      }
    }
    this.upLists()
  },

  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    let Allselected = this.data.Allselected;
    let disabled = this.data.disabled;
    let shopsGood = this.data.shopsGood;
    selectAllStatus = !selectAllStatus;
    Allselected = !Allselected;
    var shoplist = this.data.shoplist

    for (var x = 0; x < shopsGood.length; x++) {
      for (var y = 0; y < shopsGood[x].goodlist.length; y++) {
        shopsGood[x].goodlist[y].selected = selectAllStatus;
      }
    }

    for (var x = 0; x < shopsGood.length; x++) {
      shoplist[x] = selectAllStatus;
    }
    this.setData({
      shoplist: shoplist
    })


    if (selectAllStatus == true) {
      this.setData({
        disabled: false
      })
    } else {
      this.setData({
        disabled: true
      })
    }
    this.setData({
      selectAllStatus,
      Allselected,
      shopsGood
    })
    this.getTotalPrice();
    this.getTotalNum();
  },


  dropNum(e) {
    const id = e.currentTarget.dataset.id;
    let shopsGood = this.data.shopsGood;

    for (var x = 0; x < shopsGood.length; x++) {
      for (var y = 0; y < shopsGood[x].goodlist.length; y++) {
        if (shopsGood[x].goodlist[y].goodsId == id) {
          let num = shopsGood[x].goodlist[y].num;
          num--;
          if (num < 1) {
            wx.showToast({
              title: '必须买一件,或左滑删除商品',
              icon: 'none'
            })
            num = 1;
          }
          shopsGood[x].goodlist[y].num = num;
          this.setData({
            shopsGood
          })
        }
      }
    }


    this.getTotalPrice();
    this.getTotalNum();
    this.getCarNum();
    this.upLists();
  },

  addNum(e) {
    const id = e.currentTarget.dataset.id;
    let shopsGood = this.data.shopsGood;

    for (var x = 0; x < shopsGood.length; x++) {
      for (var y = 0; y < shopsGood[x].goodlist.length; y++) {
        if (shopsGood[x].goodlist[y].goodsId == id) {
          let num = shopsGood[x].goodlist[y].num;
          num++;
          if (num > shopsGood[x].goodlist[y].goodsNumber) {
            num = shopsGood[x].goodlist[y].goodsNumber
            wx.showToast({
              title: '购买数量不能大于库存量',
              icon: 'none'
            })
          }
          shopsGood[x].goodlist[y].num = num;
          this.setData({
            shopsGood
          })
        }
      }
    }
    this.getTotalPrice();
    this.getTotalNum();
    this.getCarNum();
    this.upLists();

  },


  //手动输入商品数量
  numchange: function(e) {
    console.log(e)
    var that = this;
    var shopsGood = that.data.shopsGood;
    var nums
    var goodsNumber = JSON.parse(e.currentTarget.dataset.goodsnumber)
    var id = e.currentTarget.dataset.id
    var x = JSON.parse(e.detail.value)
    if (x > goodsNumber) {
      wx.showToast({
        title: '购买数量不能大于库存数量',
        icon: 'none'
      })
      nums = goodsNumber
    } else if (x <= 0) {
      wx.showToast({
        title: '请至少购买一件商品',
        icon: 'none'
      })
      nums = 1
    } else {
      nums = x
    }

    for (var x = 0; x < shopsGood.length; x++) {
      for (var y = 0; y < shopsGood[x].goodlist.length; y++) {
        if (shopsGood[x].goodlist[y].goodsId == id) {
          shopsGood[x].goodlist[y].num = nums
        }
      }
    }

    that.setData({
      shopsGood: shopsGood
    })

    
    that.getTotalPrice();
    that.getTotalNum();
    that.getCarNum();
    that.upLists();

    that.onShow()
  },

  //对购物车商品进行分类
  cateroycar: function() {
    //shopsGood
    var that = this

    var lis = that.data.lists
    var shopsGood = [{
      goodlist: []
    }]
    if (lis.length !== 0) {
      shopsGood[0].goodlist = shopsGood[0].goodlist.concat(lis[0])
      for (var i = 1; i < lis.length; i++) {
        var k = 0;
        for (var j = 0; j < shopsGood.length; j++) {
          if (shopsGood[j].goodlist.length !== 0) {
            if (shopsGood[j].goodlist[0].createUserDeptId == lis[i].createUserDeptId) {
              shopsGood[j].goodlist = shopsGood[j].goodlist.concat(lis[i])
              k++
            }
          }
        }
        if (k == 0) {
          var li = [{
            goodlist: []
          }]
          li[0].goodlist = li[0].goodlist.concat(lis[i])
          shopsGood[shopsGood.length] = li[0]
        }
      }
    }

    that.setData({
      shopsGood: shopsGood
    })

  },

  onShow: function() {
    var that = this
    that.addcarcheck()
    if (!that.data.checklogin) {


      that.setData({
        lists: wx.getStorageSync('lists'),
      })

      wx.setStorageSync("lists", that.data.lists);
      var lis = that.data.lists;
      for (var i = 0; i < lis.length; i++) {
        if (lis[i].selected) {
          that.setData({
            disabled: false,
          })
        }
      }

      console.log('hasCarNum' + that.data.hasCarNum)
      var lists = that.data.lists
      if (lists.length > 0) {
        that.setData({
          hasCarNum: true
        })


        that.cateroycar()
        that.PutCarNum();
        that.getTotalPrice();
        that.getTotalNum();
        that.getCarNum()


        let shopsGood = that.data.shopsGood;
        var shoplist = []
        for (var i = 0; i < shopsGood.length; i++) {
          var k = 0
          for (var y = 0; y < shopsGood[i].goodlist.length; y++) {
            if (shopsGood[i].goodlist[y].selected) {
              k++
            }
          }
          if (k == 0) {
            shoplist = shoplist.concat([false])
          } else {
            shoplist = shoplist.concat([true])
          }
        }
        that.setData({
          shoplist: shoplist
        })

        util.buycarBar()

      } else {
        that.setData({
          hasCarNum: false,
        })

        wx.setStorage({
          key: 'carNum',
          data: 0,
        })
      }
      console.log('hasCarNum' + that.data.hasCarNum)

    }
  },

  //检验登录
  addcarcheck: function() {
    if (app.globalData.hasLogin) {
      this.setData({
        checklogin: false
      })
    }
  },

  login: function() {
    wx.navigateTo({
      url: "/pages/auth/login/login"
    });
  },

  //检查订单
  checkOrder: function() {
    var that = this
    let shopsGood = that.data.shopsGood;
    var k = []
    for (var x = 0; x < shopsGood.length; x++) {
      for (var y = 0; y < shopsGood[x].goodlist.length; y++) {
        if (shopsGood[x].goodlist[y].selected) {
          k = k.concat(shopsGood[x].goodlist[y].createUserDeptId)
        }
      }
    }

    var ks = 0
    for (var x = 0; x < k.length; x++) {
      for (var y = 0; y < k.length; y++) {
        if (k[x] !== k[y]) {
          ks++
        } else {}
      }
    }

    if (ks == 0) {
      that.setData({
        ordcheck: true
      })
    } else {
      that.setData({
        ordcheck: false
      })
    }

  },

  //下订单
  purchase(e) {
    var that = this;
    var bugNum = 0;
    that.checkOrder()
    if (that.data.ordcheck) {
      that.setData({
        ordlists: that.data.noordlists
      })
      var shopsGood = that.data.shopsGood;
      bugNum = shopsGood.length;
      var ord = that.data.ordlists;
      var l = ord.lists;

      for (var x = 0; x < shopsGood.length; x++) {
        for (var y = 0; y < shopsGood[x].goodlist.length; y++) {
          if (shopsGood[x].goodlist[y].selected) {
            l = l.concat(shopsGood[x].goodlist[y])
          }
        }
      }

      ord.lists = l
      ord.totalPrice = that.data.totalPrice;
      ord.totalNum = that.data.totalNum;


      that.setData({
        ordlists: ord
      })

      wx.setStorageSync("ordlists", ord);

      wx.setStorageSync("carNum", wx.getStorageSync("carNum") - bugNum);
      wx.navigateTo({
        url: '/pages/checkout/checkout',
      })
    } else {
      wx.showToast({
        title: '请选择同一商家的商品进行下单',
        icon: 'none'
      })
    }
  },

  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: '购物车'
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})